package fm.dongman.animefm.view.fragment;


import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.MyContract;
import fm.dongman.animefm.contractlib.contract.SheetInfoContract;
import fm.dongman.animefm.view.activity.SingleActivity;
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener;
import fm.dongman.animefm.view.transform.GlideRoundTransform;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.ShareHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.animefm.view.widget.MultiStateLayout;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.modellib.model.ComicModel;
import fm.dongman.modellib.model.SheetModel;
import fm.dongman.presenterlib.presenter.SheetInfoPresenter;

/**
 * @author alex 2017.10.25
 * @description 漫单（个性漫单）详情页
 */
public class SheetDetailsFragment extends BaseFragment implements SheetInfoContract.ISheetInfoView, View.OnClickListener {
    private View layoutView;
    private MultiStateLayout mMultiStateLayout; // 多状态布局控件

    private ImageButton mIbBack;    //返回按钮
    private ImageButton mIbShare;   //分享按钮

    private TextView mTvTitle;      //标题
    private TextView mTvAuthor;     //作者
    private ImageView mAvatar;
    private TextView mTvDesc;       //描述信息
    private TextView mTvInfo;       //相关信息

    private RecyclerView mRvSheetTopicList;     //动漫列表
    private FloatingActionButton mFabCollect;   //收藏按钮
    private LinearLayout mLlUserInfoContainer;  //包裹用户信息的ViewGroup


    private static final String ARG_SHEET_ID = "sheet_id";
    private String mSheetId;
    private SheetInfoContract.ISheetInfoPresenter mPresenter;

    private ComicListAdapter mSheetComicAdapter; // 动漫列表适配器
    private List<IModel.IComicModel> mSheetComicList = new ArrayList<>(); // 漫单中的动漫数据集合
    private ImageView mIvCover;
    private AppBarLayout mAppBar;
    private int mIsCollected = 0;       //是否已收藏，0没收藏，1已收藏
    private String mUserId;

    public SheetDetailsFragment() {
    }

    public static SheetDetailsFragment getInstance(String sheetId) {
        SheetDetailsFragment fragment = new SheetDetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHEET_ID, sheetId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSheetId = getArguments().getString(ARG_SHEET_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        layoutView = inflater.inflate(R.layout.fragment_sheet_details, container, false);
        new SheetInfoPresenter(this, Injection.provideSheetInfoRepository());
        initComponents(layoutView);
        return layoutView;
    }


    /**
     * 初始化控件
     *
     * @param layoutView 根布局
     */
    private void initComponents(View layoutView) {
        mAppBar = (AppBarLayout) layoutView.findViewById(R.id.mAbSheetTopicAppBar);
        mMultiStateLayout = (MultiStateLayout) layoutView.findViewById(R.id.mSheetDetailsMultiState);
        mIvCover = (ImageView) layoutView.findViewById(R.id.mTvSheetDetailsCover);
        mTvTitle = (TextView) layoutView.findViewById(R.id.mTvSheetDetailsTitle);
        mTvDesc = (TextView) layoutView.findViewById(R.id.mTvSheetDetailsContent);
        mTvInfo = (TextView) layoutView.findViewById(R.id.mTvSheetDetailsAboutInfo);
        mIbBack = (ImageButton) layoutView.findViewById(R.id.mTvSheetDetailsBack);
        mIbShare = (ImageButton) layoutView.findViewById(R.id.mTvSheetDetailsShare);
        mTvAuthor = (TextView) layoutView.findViewById(R.id.mTvSheetDetailsAuthor);
        mAvatar = (ImageView) layoutView.findViewById(R.id.mTvSheetDetailsAvatar);
        mFabCollect = (FloatingActionButton) layoutView.findViewById(R.id.mFbSheetDetailsCollectButton);
        mLlUserInfoContainer = (LinearLayout) layoutView.findViewById(R.id.mTvSheetDetailsAuthorContainer);
        mRvSheetTopicList = (RecyclerView) layoutView.findViewById(R.id.mRvSheetTopicList);

        mFabCollect.setOnClickListener(this);
        mIbBack.setOnClickListener(this);
        mIbShare.setOnClickListener(this);
        mLlUserInfoContainer.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), SingleActivity.class);

        switch (v.getId()) {
            //分享
            case R.id.mTvSheetDetailsShare:
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_TEXT, ShareHelper.generateShareText(mTvTitle.getText().toString(), mSheetId, ShareHelper.TYPE_SHEET));
                startActivity(i);
                break;

            //收藏
            case R.id.mFbSheetDetailsCollectButton:
                //禁用收藏按钮
                mFabCollect.setEnabled(false);
                if (MyContract.Companion.getUSER_ID() != null) {
                    mPresenter.collectSheet(SheetInfoPresenter.Companion.getTYPE_MANDAN(), mSheetId, 1 - mIsCollected);
                } else {
                    intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_LOGIN());
                    ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
                }
                break;

            //查看用户
            case R.id.mTvSheetDetailsAuthorContainer:
                if (mUserId != null) {
                    intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_USER_INFO());
                    intent.putExtra(SingleActivity.Companion.getBUNDLE_EXTRA_KEY_ID(), mUserId);
                    ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
                }
                break;
            //返回
            case R.id.mTvSheetDetailsBack:
                getActivity().onBackPressed();
                break;
        }
    }


    @Override
    public void initData() {
        onStateChanged(MultiStateLayout.Companion.getLOADING());
    }

    @Override
    public void bindData() {
        mSheetComicAdapter = new ComicListAdapter(getActivity(), mSheetComicList);
        mRvSheetTopicList.setAdapter(mSheetComicAdapter);
        mRvSheetTopicList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRvSheetTopicList.addOnScrollListener(new LoadMoreRecyclerOnScrollListener(mRvSheetTopicList.getLayoutManager()) {
            @Override
            public void onLoadMore(int currentPage) {
                mPresenter.getSheetInfo(SheetInfoContract.ISheetInfoPresenter.Companion.getTYPE_MANDAN(), mSheetId, currentPage);
            }
        });
        mPresenter.getSheetInfo(SheetInfoContract.ISheetInfoPresenter.Companion.getTYPE_MANDAN(), mSheetId, 1);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showSheetInfo(@NotNull IModel.ISheetModel sheetInfo) {
        onStateChanged(MultiStateLayout.Companion.getSUCCESS());
        SheetModel model = (SheetModel) sheetInfo;
        mTvTitle.setText(model.getMandanTitle());
        mTvAuthor.setText(model.getUser().getUserName());
        mIsCollected = model.getmIsCollected();
        switchCollectedStateIcon();
        mUserId = model.getUser().getUserId();
        Glide.with(getActivity()).load(model.getUser().getAvatarUrl()).bitmapTransform(new CenterCrop(getActivity()), new GlideRoundTransform(getActivity(), 7)).into(mAvatar);
        Glide.with(getActivity()).load(model.getMandanImg()).bitmapTransform(new CenterCrop(getActivity()), new GlideRoundTransform(getActivity(), 3)).into(mIvCover);
        Glide.with(getActivity()).load(model.getMandanImg()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                Palette.from(resource).generate(new Palette.PaletteAsyncListener() {
                    @Override
                    public void onGenerated(Palette palette) {
                        int color = palette.getVibrantColor(Color.parseColor("#ff0000"));
                        ObjectAnimator.ofArgb(mAppBar, "backgroundColor", color).setDuration(300).start();
                    }
                });
            }
        });
        String summary = model.getSummary() != null && model.getSummary().trim().length() > 0 ? model.getSummary() : "没有介绍";
        mTvDesc.setText(summary);
        mTvInfo.setText(model.getCreateTime() + "  |  " + model.getAnimeCount() + "个动漫  |  " + model.getCollectCount() + "人收藏");
        mSheetComicList.clear();
        mSheetComicList.addAll(model.getmMandaList());
        mSheetComicAdapter.notifyDataSetChanged();
    }

    /**
     * 切换收藏按钮的状态
     */
    private void switchCollectedStateIcon() {
        if (mIsCollected == 1)
            mFabCollect.setImageResource(R.drawable.ic_hear_selected);
        else
            mFabCollect.setImageResource(R.drawable.ic_heart);
    }

    @Override
    public void showMoreSheetInfo(@NotNull IModel.ISheetModel sheetInfo) {
        SheetModel model = (SheetModel) sheetInfo;
        mSheetComicList.addAll(model.getmMandaList());
        mSheetComicAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCollectSucceed() {
        mIsCollected = 1 - mIsCollected;
        mFabCollect.setEnabled(true);
        switchCollectedStateIcon();
        ToastHelper.getInstance(getActivity()).showSucceed("操作成功");
    }

    @Override
    public void showCollectFailed() {
        mFabCollect.setEnabled(true);
        ToastHelper.getInstance(getActivity()).showError("操作失败");
    }

    @Override
    public void setPresenter(SheetInfoContract.ISheetInfoPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {
        onStateChanged(MultiStateLayout.Companion.getNET_ERROR());
    }

    @Override
    public void showRefreshFailed() {
        ToastHelper.getInstance(getActivity()).showError(getString(R.string.str_refresh_failed));
        onStateChanged(MultiStateLayout.Companion.getEMPTY());
    }

    /**
     * 多状态切换
     *
     * @param state 状态值 {@link MultiStateLayout.Companion}
     */
    private void onStateChanged(int state) {
        if (mMultiStateLayout != null)
            mMultiStateLayout.changeState(state);
    }

    @Override
    public void showDeleteComicsState(boolean b) {
        ToastHelper.getInstance(getActivity()).showWarn("删除" + (b ? "成功" : "失败"));
    }

    /**
     * 列表适配器
     */
    private class ComicListAdapter extends RecyclerView.Adapter<ComicListAdapter.ViewHolder> {

        private Context mContext;
        private List<IModel.IComicModel> mData;

        public ComicListAdapter(Context context, List<IModel.IComicModel> data) {
            mContext = context;
            mData = data;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(View.inflate(mContext, R.layout.item_comic_list, null));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            final ComicModel model = (ComicModel) mData.get(position);
            Glide.with(mContext)
                    .load(model.getImgUrl())
                    .bitmapTransform(new CenterCrop(mContext), new GlideRoundTransform(mContext, 2))
                    .into(holder.mCover);

            holder.mTitle.setText(model.getTitle() + "(" + model.getYear() + ")");
            holder.mSubtitle.setText("更新至" + model.getEpisodes() + "集");
            holder.mThirdTitle.setText(model.getGenre());
            holder.mInfoLeft.setText(model.getCountry());
            holder.mInfoRight.setText(model.getRateScore());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, SingleActivity.class);
                    intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_ANIME_INFO());
                    intent.putExtra(SingleActivity.Companion.getBUNDLE_EXTRA_KEY_ID(), model.getId());
                    ActivityHelper.INSTANCE.startActivity((Activity) mContext, intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView mCover;
            TextView mTitle;
            TextView mSubtitle;
            TextView mThirdTitle;
            TextView mInfoLeft;
            TextView mInfoRight;

            public ViewHolder(View itemView) {
                super(itemView);
                mCover = (ImageView) itemView.findViewById(R.id.mIvComicListCover);
                mTitle = (TextView) itemView.findViewById(R.id.mTvComicListTitle);
                mSubtitle = (TextView) itemView.findViewById(R.id.mTvComicListSubTitle);
                mThirdTitle = (TextView) itemView.findViewById(R.id.mTvComicListThirdTitle);
                mInfoLeft = (TextView) itemView.findViewById(R.id.mTvComicListLastWatchEpisode);
                mInfoRight = (TextView) itemView.findViewById(R.id.mTvComicListWatchTime);
            }
        }
    }
}
